from datetime import date, timedelta
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from goods.models import GoodsVisitCount
from users.models import User


class UserTotalCountView(APIView):
    # 指定管理员权限：非管理员用户，不能调用该视图
    permission_classes = [IsAdminUser]

    def get(self, request):
        count = User.objects.filter(is_staff=False).count()
        now_date = date.today()
        return Response({
            "count": count,
            "date": now_date
        })


class UserDayCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, requeset):
        now_date = date.today()
        count = User.objects.filter(is_staff=False, date_joined__gte=now_date).count()
        return Response({
            "count": count,
            "date": now_date
        })


class UserActiveCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        count = User.objects.filter(is_staff=False, last_login__gte=now_date).count()
        return Response({
            "count": count,
            "date": now_date
        })


class UserOrderCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        # 查询今日下单的所有用户，允许重复，查询结果是查询集
        users = User.objects.filter(is_staff=False, orders__create_time__gte=now_date)
        # print(users)
        # < QuerySet[ < User: python >, < User: python >, < User: python >] >
        # 利用集合元素不允许重复的特性去重，强制格式转换
        user = set(users)
        # print(user)
        count = len(user)
        return Response({
            "count": count,
            "date": now_date
        })


class UserMonthCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        start_date = now_date - timedelta(29)
        date_list = []
        for i in range(30):
            index_date = start_date + timedelta(i)
            next_date = start_date + timedelta(i + 1)
            count = User.objects.filter(is_staff=False, date_joined__lt=next_date, date_joined__gte=index_date).count()
            date_list.append({
                "count": count,
                "date": index_date
            })
        return Response(date_list)


class GoodsDayView(APIView):
    permission_classes = [IsAdminUser]
    #   自己构造返回数据格式
    def get(self, request):
        now_date = date.today()
        goods = GoodsVisitCount.objects.filter(date__gte=now_date)
        date_list = []
        for good in goods:
            count = good.count
            category = good.category.name
            date_list.append({
                "count": count,
                "category": category
            })
        return Response(date_list)
